import Vue from 'vue'
import { setInMessage, setImUnreadSeller, setImUnreadBuyer } from '@/utils/auth'
let vue = new Vue()

/*
  接口地址 /user/getToken
  请求方式 POST
  接口描述 im获取Token
*/
const imApi = process.env.IM_BASE_API
export function imGetToken(params) {
  return vue.$fly.request({
    url: imApi + '/user/getToken.json',
    method: 'post',
    params: params
  })
}

export function checkOnline(params) {
  return vue.$fly.request({
    url: imApi + '/user/checkOnline.json',
    method: 'post',
    params: params
  })
}

export function imInit() {
  const RongIMLib = RongIMLibInit()
  const im = RongIMLib.init({ appkey: process.env.IM_APPKEY })
  return im
}
export function RongIMLibInit() {
  const RongIMLibRequire = require('@/utils/RongIMLib-3.0.7.2-dev.es.js')
  return RongIMLibRequire.default
}

export function imWatch() {
  // console.log('imWatch')
  const im = imInit()
  im.watch({
    conversation(event) {
    },
    message(event) {
      var message = event.message
      setInMessage('1')
      console.log('11收到新消息:', message)
      imConnectEls()
      setTimeout(() => {
        setInMessage('0')
      }, 50)
    },
    status(event) {
      var status = event.status
      console.log('11连接状态码:', status)
    }
  })
  return im
}

export function imConnectEls() {
  if (!vue.getImTokenData) return
  const im = imInit()
  im.connect({ token: vue.getImTokenData }).then(user => {
    console.log('all 链接成功, 链接用户 id 为: ', user.id)
    getImTotalUnreadEls()
  }).catch(error => {
    if (error.code !== 34001) {
      console.log('all 链接失败: ', error.code, error.msg)
      return
    }
    console.log('all 链接失败: ', error.code, error.msg)
    getImTotalUnreadEls()
  })
}

export function getImTotalUnreadEls() {
  const im = imInit()
  im.Conversation.getTotalUnreadCount().then(function(totalUnreadCount) {
    setImUnreadBuyer(totalUnreadCount)
  })
  const RongIMLib = RongIMLibInit()
  let conversation = im.Conversation.get({
    targetId: vue.getMemberId,
    type: RongIMLib.CONVERSATION_TYPE.PRIVATE
  })
  conversation.getUnreadCount().then(function(count) {
    setImUnreadSeller(count)
  })
}
